package cn.zoujiedev.netty.core.handler;

import cn.zoujiedev.netty.core.bean.Header;
import cn.zoujiedev.netty.core.bean.MessageType;
import cn.zoujiedev.netty.core.bean.NettyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;

/**
 * @Classname LoginAuthRespHandler
 * @Description
 * @Date 2022-11-3 16:18
 * @Created by zoujie
 */
@Slf4j
public class LoginAuthRespHandler extends ChannelInboundHandlerAdapter {

  private Map<String,Boolean> nodeCheck = new ConcurrentHashMap<>();

  private String[] whiteList = {"127.0.0.1","192.168.0.44"};

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    NettyMessage respMsg;
    if(message.getHeader() != null && message.getHeader().getType() == MessageType.HAND_SHAKE_REQUEST){

      String nodeAddr = ctx.channel().remoteAddress().toString();
      if(nodeCheck.containsKey(nodeAddr)){
        respMsg = buildResp((byte) -1);
      }else {
        String ip = ((InetSocketAddress)(ctx.channel().remoteAddress())).getHostString();
        boolean isOK = false;
        for (String wip : whiteList){
          if(wip.equals(ip)){
            isOK = true;
            break;
          }
        }

        respMsg = isOK ? buildResp((byte) 0) : buildResp((byte) -1);
        if(isOK){
          nodeCheck.put(ip,true);
        }
      }

      log.info("The login response is: {}, body: [{}]",respMsg,respMsg.getBody());
      ctx.writeAndFlush(respMsg);
    }else {
      ctx.fireChannelRead(msg);
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.fireExceptionCaught(cause);
  }

  private NettyMessage buildResp(byte res){
    NettyMessage message = new NettyMessage();

    Header header = new Header();
    header.setType(MessageType.HAND_SHAKE_RESPONSE);

    message.setHeader(header);
    message.setBody(res);

    return message;
  }
}
